import React, { useEffect, useState } from 'react';
import { Card, Typography, Spin, Empty, Row, Col, Rate, Button } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import recommendationService from '../../services/RecommendationService';
import { useNavigate } from 'react-router-dom';
import '../../styles/MovieRecommend.css';

const { Title, Text } = Typography;

const UpcomingMovie = () => {
  const [movies, setMovies] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const navigate = useNavigate();
  
  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        const result = await recommendationService.getUpcomingMovies(20);
        if (result.success) {
          setMovies(result.data);
        } else {
          setError(result.message || '获取数据失败');
        }
      } catch (error) {
        setError('网络错误，请稍后重试');
      } finally {
        setLoading(false);
      }
    };
    loadData();
  }, []);

  const renderMovieCard = (movie) => {
    const isNoRating = movie.rating === 0 || movie.rating === null || movie.rating === undefined;
    const rating = isNoRating ? '暂无评分' : (typeof movie.rating === 'number' ? movie.rating.toFixed(1) : (isNaN(parseFloat(movie.rating)) ? '暂无评分' : parseFloat(movie.rating).toFixed(1)));

    return (
      <Col xs={24} sm={12} md={8} lg={6} key={movie.id} className="movie-recommend-col">
        <Card
          hoverable
          className="movie-recommend"
          cover={
            <div>
              <img src={movie.poster_url} alt={movie.title} />
              <img
                src={movie.poster_url}
                alt={movie.title}
                onClick={() => navigate(`/recommendation/movie-detail/${movie.id}?source=maoyan`)}
              />
            </div>
          }
          onClick={() => navigate(`/recommendation/movie-detail/${movie.id}?source=maoyan`)}
        >
          <Title level={5}>{movie.title}</Title>
          <div className="movie-recommend-movie-info">
            {isNoRating ? (
              <Text type="secondary">{rating}</Text>
            ) : (
              <div className="movie-recommend-rating">
                <Rate disabled allowHalf defaultValue={movie.rating / 2} />
                <Text strong>{rating}</Text>
              </div>
            )}
          </div>
          <Text type="secondary">
            {movie.year} · {movie.genre.join(' / ')}
          </Text>
        </Card>
      </Col>
    );
  };

  return (
    <div className="movie-recommend">
      <Button
        onClick={() => navigate(-1)}
        icon={<ArrowLeftOutlined />}
        className="movie-recommend-back-button"
      >
        返回
      </Button>
      {loading ? (
        <div className="movie-recommend-loading">
          <Spin size="large" tip="加载即将上映电影中..." />
        </div>
      ) : error ? (
        <div className="movie-recommend-error">{error}</div>
      ) : movies.length === 0 ? (
        <Empty description="暂无即将上映电影数据" />
      ) : (
        <Row gutter={[16, 16]}>{movies.map(renderMovieCard)}</Row>
      )}
    </div>
  );
};

export default UpcomingMovie;